# coding: utf-8

import datetime, sys, SocketServer,time
import tornado.httpserver
import tornado.ioloop
from tornado.options import define, options
import tornado.web
import tornado.database
import tornado.escape
import gearman
import urlparse
import urllib
import re
import os
import gzip,zlib
from cStringIO import StringIO
import json
import binascii
import iso8601
sys.path.append('/home/jiaqi/project/beacon/')
from apiResponse_server_config import gearman_port
sys.path.append('/home/function/')
import Basic

reload (sys)
sys.setdefaultencoding('utf-8')

log_folder = "/var/log/api_response_error"
#client = gearman.GearmanClient(["localhost:4730"])

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
                (r"/open[/]*", app_api),
                (r"/qyer/v0[/]*", app_sdk),
                (r"/$", apiResponse)
                ]
        settings = dict(
                debug = False,
                )
        tornado.web.Application.__init__(self, handlers, **settings)


class app_api(tornado.web.RequestHandler):
    global log_folder
    def post(self):
        successful = False
        try:
            #time.sleep(0.01)
            self.client = gearman.GearmanClient(gearman_port)
            #时间修改为服务器时间
            self.timestamp = int(time.time())
            
            #print self.data_file2
            self.client.submit_job("app_api", json.dumps({"data":self.request.arguments,"servertime":self.timestamp}), background=True)
            successful = True
            
        except Exception,e:
            print e
            self.writeErrorLog("POST = %s" % (e))
            self.writeLog("Exception type = %s" % (sys.exc_type))
            self.writeLog("Exception = %s" % (sys.exc_value))
            self.writeLog("Exception Trace= %s" % (sys.exc_traceback))
            self.write(json.dumps({"successful":"False",'error':'Final : %s' % e}))
        #self.set_status(204)
        if successful:
            self.write(json.dumps({"successful":"true"}))
            
            #pass
        self.finish()

        arguments_dic = {}
        for key,value in self.request.arguments.items():
            arguments_dic[key] = value[0]
        Basic.urlRequest("http://api_response1.qyer.com/open" , "*/*" ,arguments_dic)


    def get(self):
        successful = False
        try:
            #time.sleep(0.01)
            self.client = gearman.GearmanClient(gearman_port)
            #时间修改为服务器时间
            self.timestamp = int(time.time())
            
            #print self.data_file2
            self.client.submit_job("app_api", json.dumps({"data":self.request.arguments,"servertime":self.timestamp}), background=True)
            successful = True
                

        except Exception,e:
            print e
            self.writeErrorLog("POST = %s" % (e))
            self.writeLog("Exception type = %s" % (sys.exc_type))
            self.writeLog("Exception = %s" % (sys.exc_value))
            self.writeLog("Exception Trace= %s" % (sys.exc_traceback))
            self.write(json.dumps({"successful":"False",'error':'Final : %s' % e}))
        #self.set_status(204)
        if successful:
            self.write(json.dumps({"successful":"true"}))
            
            #pass
        self.finish()
        arguments_dic = {}
        for key,value in self.request.arguments.items():
            arguments_dic[key] = value[0]
        Basic.urlRequest("http://api_response1.qyer.com/open" , "*/*" ,arguments_dic)
        

    def writeLog(self, message, log_file = "{0}/error_log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'aw') as f:
            f.write(line)

    def writeErrorLog(self, message, log_file = "{0}/error_log.log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'w') as f:
            f.write(line)
 

class app_sdk(tornado.web.RequestHandler):
    global log_folder
    def post(self):
        successful = False
        try:
            #time.sleep(0.01)
            self.client = gearman.GearmanClient(gearman_port)
            #时间修改为服务器时间
            self.timestamp = int(time.time())
            
            #print self.data_file2
            self.client.submit_job("app_beacon", json.dumps({"data":self.request.arguments,"servertime":self.timestamp}), background=True)
            successful = True
                

        except Exception,e:
            print e
            self.writeErrorLog("POST = %s" % (e))
            self.writeLog("Exception type = %s" % (sys.exc_type))
            self.writeLog("Exception = %s" % (sys.exc_value))
            self.writeLog("Exception Trace= %s" % (sys.exc_traceback))
            self.write(json.dumps({"successful":"False",'error':'Final : %s' % e}))
        #self.set_status(204)
        if successful:
            self.write(json.dumps({"successful":"true"}))
            #pass
        self.finish()

    def get(self):
        successful = False
        try:
            #time.sleep(0.01)
            self.client = gearman.GearmanClient(gearman_port)
            #时间修改为服务器时间
            self.timestamp = int(time.time())
            
            #print self.data_file2
            self.client.submit_job("app_beacon", json.dumps({"data":self.request.arguments,"servertime":self.timestamp}), background=True)
            successful = True
                

        except Exception,e:
            print e
            self.writeErrorLog("POST = %s" % (e))
            self.writeLog("Exception type = %s" % (sys.exc_type))
            self.writeLog("Exception = %s" % (sys.exc_value))
            self.writeLog("Exception Trace= %s" % (sys.exc_traceback))
            self.write(json.dumps({"successful":"False",'error':'Final : %s' % e}))
        #self.set_status(204)
        if successful:
            self.write(json.dumps({"successful":"true"}))
            #pass
        self.finish()
        

    def writeLog(self, message, log_file = "{0}/error_log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'aw') as f:
            f.write(line)

    def writeErrorLog(self, message, log_file = "{0}/error_log.log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'w') as f:
            f.write(line)

class apiResponse(tornado.web.RequestHandler):
    global log_folder
    def post(self):
        successful = False
        try:
            #time.sleep(0.01)
            self.client = gearman.GearmanClient(gearman_port)
            #时间修改为服务器时间
            self.timestamp = int(time.time())
            
            #print self.data_file2
            self.client.submit_job("api_response", json.dumps({"data":self.request.arguments,"servertime":self.timestamp}), background=True)
            successful = True
                

        except Exception,e:
            print e
            self.writeErrorLog("POST = %s" % (e))
            self.writeLog("Exception type = %s" % (sys.exc_type))
            self.writeLog("Exception = %s" % (sys.exc_value))
            self.writeLog("Exception Trace= %s" % (sys.exc_traceback))
            self.write(json.dumps({"successful":"False",'error':'Final : %s' % e}))
        #self.set_status(204)
        if successful:
            self.write(json.dumps({"successful":"true"}))
            #pass
        self.finish()

    def get(self):
        successful = False
        try:
            #time.sleep(0.01)
            self.client = gearman.GearmanClient(gearman_port)
            #时间修改为服务器时间
            self.timestamp = int(time.time())
            
            #print self.data_file2
            self.client.submit_job("api_response", json.dumps({"data":self.request.arguments,"servertime":self.timestamp}), background=True)
            successful = True
                

        except Exception,e:
            print e
            self.writeErrorLog("POST = %s" % (e))
            self.writeLog("Exception type = %s" % (sys.exc_type))
            self.writeLog("Exception = %s" % (sys.exc_value))
            self.writeLog("Exception Trace= %s" % (sys.exc_traceback))
            self.write(json.dumps({"successful":"False",'error':'Final : %s' % e}))
        #self.set_status(204)
        if successful:
            self.write(json.dumps({"successful":"true"}))
            #pass
        self.finish()
        

    def writeLog(self, message, log_file = "{0}/error_log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'aw') as f:
            f.write(line)

    def writeErrorLog(self, message, log_file = "{0}/error_log.log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'w') as f:
            f.write(line)


'''class MyHandler(tornado.web.RequestHandler):
    global log_folder

    def get(self):
        successful = False
        try:
            #time.sleep(0.01)
            self.client = gearman.GearmanClient(gearman_port)
            #时间修改为服务器时间
            self.timestamp = int(time.time()*1000)
            #从请求头里面获取ip
            self.ip = self.request.remote_ip
            #从请求头里面获取浏览器信息
            self.user_agent = self.request.headers.get("User-Agent","")
            
            #print self.data_file2
            self.client.submit_job("beacon", json.dumps({"data":self.request.arguments,"servertime":self.timestamp,"ip":self.ip,"User-Agent":self.user_agent}), background=True)
            successful = True
                

        except Exception,e:
            print e
            self.writeErrorLog("GET = %s" % (e))
            self.writeLog("Exception type = %s" % (sys.exc_type))
            self.writeLog("Exception = %s" % (sys.exc_value))
            self.writeLog("Exception Trace= %s" % (sys.exc_traceback))
            self.write(json.dumps({"successful":"False",'error':'Final : %s' % e}))
        
        self.set_status(204)
        self.finish()
        

    def writeLog(self, message, log_file = "{0}/error_log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'aw') as f:
            f.write(line)

    def writeErrorLog(self, message, log_file = "{0}/error_log.log".format(log_folder)):
        line = "[%s] %s\n" % (datetime.datetime.now(), message)
        with open(log_file, 'w') as f:
            f.write(line)'''

def main(argv):
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    http_server.listen(int(argv[1]))
    tornado.ioloop.IOLoop.instance().start()
    print "start listening..."

if __name__ == "__main__":
    main(sys.argv)

